// auth.js - 五子棋平台用户认证逻辑
class AuthApp {
    constructor() {
        // 初始化用户数据存储
        this.users = JSON.parse(localStorage.getItem('gomoku_users')) || [];
        
        // 检查是否已有登录用户
        const currentUser = JSON.parse(localStorage.getItem('gomoku_currentUser'));
        if (currentUser) {
            window.location.href = 'index.html';
        }
        
        this.setupEventListeners();
    }
    
    setupEventListeners() {
        // 登录表单提交
        document.getElementById('loginForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.login();
        });
        
        // 注册表单提交
        document.getElementById('registerForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.register();
        });
        
        // 游客登录按钮
        document.getElementById('guestLogin').addEventListener('click', () => {
            this.guestLogin();
        });
        
        // 添加表单切换时的清除功能
        document.querySelectorAll('.nav-link').forEach(link => {
            link.addEventListener('click', () => {
                this.clearFormMessages();
            });
        });
    }
    
    login() {
        const username = document.getElementById('loginUsername').value.trim();
        const password = document.getElementById('loginPassword').value;
        
        // 验证输入
        if (!username || !password) {
            this.showMessage('loginForm', '请输入用户名和密码', 'danger');
            return;
        }
        
        // 查找用户
        const user = this.users.find(u => u.username === username && u.password === password);
        
        if (user) {
            // 创建当前用户会话
            const currentUser = {
                username: user.username,
                token: user.token,
                isGuest: false
            };
            
            localStorage.setItem('gomoku_currentUser', JSON.stringify(currentUser));
            window.location.href = 'index.html';
        } else {
            this.showMessage('loginForm', '用户名或密码错误', 'danger');
        }
    }
    
    register() {
        const username = document.getElementById('registerUsername').value.trim();
        const password = document.getElementById('registerPassword').value;
        const confirm = document.getElementById('registerConfirm').value;
        
        // 验证输入
        if (!username || !password || !confirm) {
            this.showMessage('registerForm', '请填写所有字段', 'danger');
            return;
        }
        
        if (password !== confirm) {
            this.showMessage('registerForm', '两次输入的密码不一致', 'danger');
            return;
        }
        
        if (password.length < 6) {
            this.showMessage('registerForm', '密码长度至少为6位', 'danger');
            return;
        }
        
        // 检查用户名是否已存在
        if (this.users.some(u => u.username === username)) {
            this.showMessage('registerForm', '用户名已存在', 'danger');
            return;
        }
        
        // 创建新用户
        const newUser = {
            username,
            password,
            token: 'usr_' + Math.random().toString(36).substr(2, 12),
            joinDate: new Date().toISOString()
        };
        
        // 保存用户
        this.users.push(newUser);
        localStorage.setItem('gomoku_users', JSON.stringify(this.users));
        
        // 自动登录
        const currentUser = {
            username: newUser.username,
            token: newUser.token,
            isGuest: false
        };
        
        localStorage.setItem('gomoku_currentUser', JSON.stringify(currentUser));
        
        // 显示成功消息并跳转
        this.showMessage('registerForm', '注册成功！即将跳转...', 'success');
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 1500);
    }
    
    guestLogin() {
        // 创建临时游客用户
        const guestId = 'guest_' + Math.random().toString(36).substr(2, 9);
        const guestName = `游客_${Math.floor(Math.random() * 10000)}`;
        
        const currentUser = {
            username: guestName,
            token: guestId,
            isGuest: true
        };
        
        localStorage.setItem('gomoku_currentUser', JSON.stringify(currentUser));
        
        // 显示成功消息并跳转
        this.showMessage('guest', `欢迎游客 ${guestName}！即将跳转...`, 'success');
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 1500);
    }
    
    showMessage(formId, text, type) {
        this.clearFormMessages();
        
        const form = document.getElementById(formId);
        const messageDiv = document.createElement('div');
        messageDiv.className = `alert alert-${type} mt-3`;
        messageDiv.textContent = text;
        
        form.appendChild(messageDiv);
        
        // 自动消失
        if (type === 'success') {
            setTimeout(() => {
                messageDiv.remove();
            }, 3000);
        }
    }
    
    clearFormMessages() {
        document.querySelectorAll('.alert').forEach(alert => {
            alert.remove();
        });
    }
}

// 初始化认证应用
document.addEventListener('DOMContentLoaded', () => {
    new AuthApp();
});